<?php

namespace common\components\image_beds\wbed;

use common\components\fs\Fs;
use common\components\wtools\tools\Model;
use common\models\db\Files;
use yii\di\Instance;

class WbedFs extends Fs
{
    public static function getComponentId(): string
    {
        return 'wbedFs';
    }

    /**
     * @var Wbed $wbed
     */
    public $wbed = 'wbed';

    public function init()
    {
        $this->wbed = Instance::ensure($this->wbed, Wbed::className());
        parent::init();
    }

    public function uploadBase64($idFileName, $base64)
    {
        $url = $this->wbed->uploadByBase64($base64, $idFileName);
        return $url;
    }

    /**
     * @return Files|null
     * @throws \yii\base\Exception
     */
    public function saveFile($url)
    {
        $this->file->locate_path = str_replace($this->wbed->baseUrl, '', $url);
        $this->file->locate_path = dirname($this->file->locate_path);
        if (!$this->file->save()) {
            throw new \Exception("文件保存失败：".Model::getModelError($this->file));
        }
        return $this->file;
    }

    /**
     * @return string
     */
    public function getAbUrl()
    {
        return $this->wbed->baseUrl . $this->file->locate_path. '/'. $this->file->filename;
    }
}